﻿// -----------------------------------------------------------------------
//  <copyright file="ValidationExceptionHandler.cs" company="LiuliuSoft">
//      Copyright (c) 2025 66SOFT. All rights reserved.
//  </copyright>
//  <site>https://ifs.66soft.net</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-11-07 00:11</last-date>
// -----------------------------------------------------------------------

using DaprPlus.AspNetCore.Mvc.Filters;
using DaprPlus.Domain;

using FluentValidation;

using Microsoft.AspNetCore.Mvc.Filters;


namespace DaprPlus.MediatR;

/// <summary>
/// 验证异常处理器
/// </summary>
public class ValidationExceptionHandler : ApiResultExceptionHandlerBase
{
    /// <inheritdoc />
    public override int Priority => 300;

    /// <inheritdoc />
    public override bool CanHandle(Exception exception)
    {
        return exception is ValidationException;
    }

    protected override bool SetJsonErrorResult(ActionExecutedContext context, string message, ApiResultType resultType = ApiResultType.Error)
    {
        if (!context.HttpContext.Response.HasStarted)
        {
            var result = new ApiResult(message, resultType);
            context.Result = new ObjectResult(result) { StatusCode = 200 };
        }

        context.ExceptionHandled = true;
        return true;
    }

    /// <inheritdoc />
    protected override string GetFriendlyMessage(Exception exception)
    {
        if (exception is not ValidationException validationException)
        {
            return exception.Message;
        }

        // 如果有验证错误集合，格式化所有错误消息
        if (validationException.Errors != null && validationException.Errors.Any())
        {
            var failureDict = validationException.Errors
                .GroupBy(e => e.PropertyName, e => e.ErrorMessage)
                .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray());

            return string.Join("; ", failureDict.Select(kv =>
                string.IsNullOrEmpty(kv.Key)
                    ? string.Join(" ", kv.Value)
                    : $"{kv.Key}: {string.Join(" ", kv.Value)}"));
        }

        // 如果没有错误集合，使用异常消息
        return validationException.Message;
    }
}